#include <SD.h>
#include <SPI.h>

#define AIRBAG_1_CONTROLLER_PIN 41
#define AIRBAG_2_CONTROLLER_PIN 43  
#define AIRBAG_3_CONTROLLER_PIN 45
#define AIRPUMP_CONTROLLER_PIN  39  

#define PILLOW_LEFT_PIN   53
#define PILLOW_MIDDLE_PIN 51
#define PILLOW_RIGHT_PIN  49
#define SNORE_INPUT_PIN   47


#define SERIAL_SETUP
#ifdef  SERIAL_SETUP
#define print_info(msg)    Serial.println(String("[ INFO] ") + String((msg)))
#define print_err(err_msg) Serial.println(String("[ERROR] ") + String((err_msg)))
#endif

/*
 * global variables
 */
bool press_state[] = {0,0,0};
bool is_snoring = false;
String str;

inline void init_airbag(){
  pinMode(PILLOW_LEFT_PIN, INPUT);
  pinMode(PILLOW_MIDDLE_PIN, INPUT);
  pinMode(PILLOW_RIGHT_PIN, INPUT);
  
  pinMode(SNORE_INPUT_PIN, INPUT);

  pinMode(AIRBAG_1_CONTROLLER_PIN, OUTPUT);
  pinMode(AIRBAG_2_CONTROLLER_PIN, OUTPUT);
  pinMode(AIRBAG_3_CONTROLLER_PIN, OUTPUT);

  pinMode(AIRPUMP_CONTROLLER_PIN, OUTPUT);
}

inline void read_press_state(){
  press_state[0] = digitalRead(PILLOW_LEFT_PIN);
  press_state[1] = digitalRead(PILLOW_MIDDLE_PIN);
  press_state[2] = digitalRead(PILLOW_RIGHT_PIN);
}

inline void recognize_snore(){
  is_snoring = digitalRead(SNORE_INPUT_PIN);
}

inline void write_press_state(){
  digitalWrite(AIRBAG_1_CONTROLLER_PIN, press_state[0]);
  digitalWrite(AIRBAG_2_CONTROLLER_PIN, press_state[1]);
  digitalWrite(AIRBAG_3_CONTROLLER_PIN, press_state[2]);
}

void setup() {
  Serial.begin(9600);
  while(!Serial){} // wait for serial port to connect. Needed for native USB.
  init_airbag();
  
}

void loop() {
  read_press_state();
  Serial.print("pillow left press state: ");
  str = press_state[0]?"true" : "false";
  Serial.println(str);
  Serial.print("pillow middle press state: ");
  str = press_state[1]?"true" : "false";
  Serial.println(str);
  Serial.print("pillow right press state: ");
  str = press_state[2]?"true" : "false";
  Serial.println(str);
 
  recognize_snore();
  Serial.print("recognize snore result: ");
  str = is_snoring?"true" : "false";
  Serial.println(str);

  write_press_state();
  Serial.print("left airbag state: ");
  str = press_state[0]?"open" : "close";
  Serial.println(str);
  Serial.print("middle airbag state: ");
  str = press_state[1]?"open" : "close";
  Serial.println(str);
  Serial.print("right airbag state: ");
  str = press_state[2]?"open" : "close";
  Serial.println(str);

  if(is_snoring && (press_state[0] || press_state[1] || press_state[2])){
    digitalWrite(AIRPUMP_CONTROLLER_PIN, HIGH);
    Serial.println("airpump state: open");
  }else{
    digitalWrite(AIRPUMP_CONTROLLER_PIN, LOW);
    Serial.println("airpump state: close");
  }

}
